#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2021-09-29 4:56 下午
# @Author  : yangdy
# @File    : gevent_simple
# @Software: PyCharmCE
import random
import gevent
from gevent import Greenlet


def foo():
    print('running in foo')
    gevent.sleep(0)
    print('com back from bar in to foo')


def bar():
    print('running in bar')
    gevent.sleep(0)
    print('com back from foo in to bar')


# foo bar
gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar),
])

m = {}


# task
def task(pid):
    print('Task %s start...' % pid)
    # gevent.sleep(random.randint(0, 2) * 0.001)
    m[pid] = 0
    for i in range(1000000):
        m[pid] += i
    print('Task %s done' % pid, m[pid])


def synchronous():
    for i in range(1, 10):
        task(i)


def asynchronous():
    threads = [gevent.spawn(task, i) for i in range(10)]
    gevent.joinall(threads)


print('Synchronous:')
synchronous()

print('Asynchronous:')
asynchronous()


# class
class Test(Greenlet):
    def __init__(self, message, n):
        Greenlet.__init__(self)
        self.message = message
        self.n = n

    def _run(self):
        print(self.message, 'start')
        # gevent.sleep(self.n)
        a = 1
        for i in range(1, self.n):
            a *= i
        print(self.message, 'end')
        # print(a)


tests = [
    Test("hello", 30000),
    Test("world", 20000),
    Test("world2", 33000),
    Test("world3", 13000),
]

# start
for test in tests:
    test.start()

# wait for end of run
for test in tests:
    test.join()
